﻿using System.Windows.Media;
using System.Windows.Media.Imaging;
using Zive.Color;

namespace LabColorPicker {

    public class RgbTwoChannelBitmapMaker: TwoChannelBitmapMaker<RgbColor, RgbChannels> {

        private bool _dirty;

        private RgbTwoChannelBitmapMaker( ) { }
        public RgbTwoChannelBitmapMaker( int width, int height ) {
            _width = width;
            _height = height;
        }

        private readonly int _width;
        public override int Width {
            get { return _width; }
        }

        private readonly int _height;
        public override int Height {
            get { return _height; }
        }

        private BitmapSource _bitmap;
        public override BitmapSource Bitmap {
            get {
                if ( _dirty ) {
                    _dirty = false;
                    _bitmap = _UpdateBitmap( );
                }
                return _bitmap;
            }
        }

        private RgbColor _color;
        public override RgbColor Color {
            get { return _color; }
            set {
                _color = value;
                _dirty = true;
            }
        }

        private RgbChannels _horizontalChannel;
        public override RgbChannels HorizontalChannel {
            get { return _horizontalChannel; }
            set {
                _horizontalChannel = value;
                _dirty = true;
            }
        }

        private RgbChannels _verticalChannel;
        public override RgbChannels VerticalChannel {
            get { return _verticalChannel; }
            set {
                _verticalChannel = value;
                _dirty = true;
            }
        }

        protected override BitmapSource _UpdateBitmap( ) {
            int stride = _width * 3;

            var pixels = new byte[ _height * stride ];
            int index = 0;

            var rgb = Color.Clone( );

            var h = _height - 1;
            var w = _width - 1;
            for ( var y = h; y >= 0; y-- ) {
                for ( var x = 0; x < _width; x++ ) {
                    rgb[ _verticalChannel ] = (double) y / (double) h * 255d;
                    rgb[ _horizontalChannel ] = (double) x / (double) w * 255d;

                    pixels[ index++ ] = rgb.ByteR;
                    pixels[ index++ ] = rgb.ByteG;
                    pixels[ index++ ] = rgb.ByteB;
                }
            }

            return BitmapSource.Create( _width, _height, 96, 96, PixelFormats.Rgb24, null, pixels, stride );
        }

    }

}
